import React from 'react';
import { connect } from 'dva';
import ReactEcharts from 'echarts-for-react';
import moment from 'moment';
import {Layout, Button, Row, Col, DatePicker, Select, Divider, Checkbox,notification, message} from 'antd';
import Gmap from "@/utils/HshMap/Gmap";
import {FullScreen} from "ol/control";
import GclusterConvexhul from '@/utils/HshMap/GclusterConvexhul';
import styles from "../BirdsMonitoring/index.less";
import Legend from "ol-ext/control/Legend";
import Gstyle from "@/utils/HshMap/Gstyle";
import PublicInterface from "@/utils/Common/PublicInterface";
import './index.module.css'

const { RangePicker } = DatePicker;
const { Content, Sider  } = Layout;
const { Option } = Select;

const dateFormat = 'YYYY-MM-DD';
const endDateStr = moment().format(dateFormat);
const startDateStr = moment().month(moment().month() -3).format(dateFormat);
const bodyWidth = document.body.clientWidth;
const bodyHeight = document.body.clientHeight;

@connect(({ birdsMonitor,...hydrological }) => ({ birdsMonitor,...hydrological }))
class BirdsMonitoring extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      birdsUrl: null,
      tableId: null,
      birdsInfo: {},
      visible:false,
      isopen: false,
      time: null,
      birdTypes:[],
      endDateStr,
      startDateStr,
      width: 1366,
      height: 768,
      timeStatus: 0,
      legend: null,
      currIndexContent: ''
    }
    this.gmap = new Gmap();
    this.gmap.initMap();
    this.gmap.map.addControl(new FullScreen({tipLabel: '全屏切换'}));
  }

  handleOk = e => {
    this.setState({
      visible: false,
    });
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  getEcharOptions = () => {
    return {
        yAxis: { type: 'value' },
        xAxis: {
          type: 'category',
          axisLabel: {
            interval: 0,
            rotate: -50
          },
          data: [],
          dataField: 'birdTypeNames',
        },
        series: [
          {
            name: '统计结果',
            type: 'bar',
            barCategoryGap: '30%',
            itemStyle: { normal: { color: '#3ec480' } },
            data: [],
            dataField: 'birdCnt',
          },
        ],
      }
  }

  componentDidMount() {
    this.init();
    this.gmap.map.setTarget('birdsMonitoringMap');
    // Define a new legend
    // this.state.legend = new Legend({
    //   title: '图例',
    //   style: '',
    //   collapsed: false,
    //   collapsible: true,
    //   // margin: 10,
    //   size: [24, 24]
    // });
    // this.gmap.map.addControl(this.state.legend);

    // 窗口resize 监听
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
  }

  componentWillUnmount(){
    notification.destroy()
  }

  init = () => {
    this.queryServer();
    var publicInterface = new PublicInterface();
    var self = this;
    //图层列表没有，请求配置服务接口
    publicInterface.mapConfigList(this.props,'鸟类监测',function (data) {
      if (data && data.data.length > 0) {
        data.data.map(ele => {
          if (ele.mapName == '鸟类监测') {
            self.setState({
              birdsUrl: ele.netUrl + ele.url,
              tableId: ele.tableId
            })
          }
        });
      }
    });

    this.hydrologyContentQuery()
  }
  // ajax请求
  queryServer = () => {
    const { dispatch } = this.props;
    //查询鸟类名称
    dispatch({
      type: 'birdsMonitor/birdNamesQuery',
      payload: {},
    });
    //鸟类概览（数量与种类数量）
    dispatch({
      type: 'birdsMonitor/birdGeneral',
      payload: {},
    });
  }
  // 取父div的height
  handleResize = () => {
    const self = this;
    const divWidth = document.body.clientWidth;
    const divHeight = document.body.clientHeight;
    this.setState({ width: divWidth, height: divHeight - 66 });
    setTimeout(function () {
      self.gmap.map.updateSize();
    }, 100);
  };

  //检测内容查询
  hydrologyContentQuery = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'hydrological/hydrologyContentQuery',
      payload: {
        "dictKey":"ecology_cluster_type"
      },
    });
  };

  selectContentChange = (value) => {
    this.setState({
      currIndexContent: value
    })
  }

  //选择鸟类
  birdChange = (e) => {
    let exist = false;
    for(var i = 0; i < this.state.birdTypes.length; i++){
      if(this.state.birdTypes[i] == e.target.value){
        this.state.birdTypes.splice(i,1);
        exist = true;
      }
    }
    if(!exist){
      this.state.birdTypes.push(e.target.value);
    }
  }
  //新增legend
  legendAddRow = (birdsInfo,titleName) => {
    var styleBirds = Gstyle.styleBirdsDictionary(birdsInfo);
    this.state.legend.addRow({
      title: titleName ,
      typeGeom: "Point",
      style: styleBirds[titleName],
    });
    this.state.legend.refresh();
  }

  //统计
  birdCount = () => {
    const { dispatch } = this.props;
    const {birdTypes,startDateStr,endDateStr,birdsInfo, tableId,birdsUrl} = this.state;
    // console.log(birdTypes,'-----')
    //将选中的鸟类名称数组已字符串的形式传给后台
    let birdTypeStr = "'" +this.state.currIndexContent + "'";
    // for(var i = 0; i < birdTypes.length; i++){
    //   if(i==0){
    //     birdTypeStr += "'" + birdTypes[i] + "'";
    //   }else{
    //     birdTypeStr +=",'"+ birdTypes[i] + "'";
    //   }
    // }

    if(this.state.currIndexContent!=''){
      this.gclusterConvexhul = new GclusterConvexhul();
      this.gclusterConvexhul.clusterLayerFun(dispatch, this.gmap.map,birdsInfo,this.state.currIndexContent,startDateStr,endDateStr,birdsUrl);
      //删除后新增
      // this.gmap.map.removeControl(this.state.legend);
      // this.state.legend = new Legend({
      //   title: '图例',
      //   style: '',
      //   collapsed: false,
      //   collapsible: true,
      //   size: [24, 24]
      // });
      // this.gmap.map.addControl(this.state.legend);
      // for (let m = 0; m < birdTypes.length; m++) {
      //   this.legendAddRow(birdsInfo,birdTypes[m]);
      // }

      // dispatch({
      //   type: 'birdsMonitor/birdCount',
      //   payload: {birdTypes:birdTypeStr,
      //     startDateStr: startDateStr,
      //     endDateStr:endDateStr,},
      // }).then(response => {
      //   let des = null;
      //   let _echartsOption = this.getEcharOptions();
      //   if (response && response.success) {
      //     _echartsOption.xAxis.data = response.data[_echartsOption.xAxis.dataField];
      //     const { series } = _echartsOption;
      //     series.map(ele => {
      //       ele.data = response.data[ele.dataField];
      //     });
      //     des = (<ReactEcharts
      //       option={_echartsOption}
      //       notMerge={true}
      //       lazyUpdate={true}
      //       style={{ width: '100%'}}
      //     />)
      //   }
        // this.openBirdCountModel(des);
      // });
    }else{
      this.openBirdCountModel("未选择类型！")
    }
  }

  /**
   * 打开鸟类统计弹框
   * @param des
   */
  openBirdCountModel = (des) => {
    const duration = typeof des === 'string' ? 3 : null;
    message.warning(des);
    // notification.open({
    //   key: 'birdCount',
    //   duration,
    //   message: '提示',
    //   description: des,
    //   placement: 'centerTop',
    //   bottom: 10
    // });
  }

  //近三月  近两月  近半年时间选择
  handleChangeTime = (index) => {
    this.setState({
      timeStatus: index,
      endDateStr: moment().format('YYYY-MM-DD'),
      timeStamp: new Date()+index*10
    });
    if(index == 0){
      this.setState({
        startDateStr: moment().add(-3,'month').format('YYYY-MM-DD')
      });
    }else if(index == 1){
      this.setState({
        startDateStr: moment().add(-2,'month').format('YYYY-MM-DD')
      });
    }else{
      this.setState({
        startDateStr: moment().add(-6,'month').format('YYYY-MM-DD')
      });
    }
  }

  //时间选择
  dataChange = (date, dateString) => {
    this.setState({
      startDateStr:dateString[0],
      endDateStr:dateString[1],
      timeStatus: -1
    });
  }

  render() {
    const {birdGeneral,birdNames,birdCount} = this.props.birdsMonitor;
    const { birdsInfo } = this.state
    let birdRowList = [];
    let lastBirdName = null;
    for (var i = 0;i < birdNames.length;i++){
      //保存字典值
      birdsInfo[birdNames[i].code] = birdNames[i].name;
      if(i%2 == 1){
        birdRowList.push(<Row type="flex" justify="space-around" style={{padding: '5px' }} key={i}>
                            <Col span={12} style={{textAlign:'left'}}><Checkbox className={styles.birdCheckbox} onChange={this.birdChange} value={lastBirdName.name}>{lastBirdName.name}</Checkbox></Col>
                            <Col span={12} style={{textAlign:'left'}}><Checkbox className={styles.birdCheckbox} onChange={this.birdChange} value={birdNames[i].name}>{birdNames[i].name}</Checkbox></Col>
                          </Row>)
      }else{
        lastBirdName = birdNames[i]
        if(i == birdNames.length -1 ){
          birdRowList.push(<Row type="flex" justify="space-around" style={{padding: '5px'}} key={i}>
            <Col span={12} style={{textAlign:'left'}}><Checkbox className={styles.birdCheckbox} onChange={this.birdChange} value={birdNames[i].name}>{birdNames[i].name}</Checkbox></Col>
            <Col span={12} style={{textAlign:'left'}}></Col>
          </Row>)
        }
      }
    }
    let _echartsOption = this.getEcharOptions();
    _echartsOption.xAxis.data = birdCount[_echartsOption.xAxis.dataField];
    const { series } = _echartsOption;
    series.map(ele => {
      ele.data = birdCount[ele.dataField];
    });

    const {indexContent} = this.props.hydrological;
    let conSelectOptions = indexContent.map(ele => {
      return (<Option value={ele.code} key={ele.code}>{ele.name}</Option>)
    });

    return (
      <Layout>
        <Sider width={371} style={{background: 'rgba(255,255,255,0.9)', padding: '0',borderRight:'1px solid #ddd', position: 'absolute',left: 0,zIndex: 999,height: '300px'}}>
          <div style={{ background: '#EBF5EF',height: '40px',lineHeight: '40px',paddingLeft: '20px' }}><span style={{ fontSize: '12px',color:'#40AF59' }}>生态聚类监测</span></div>
          <div style={{padding: '20px' ,height:(bodyHeight - 108), overflowY: 'auto',fontSize: '12px',color: '#333'  }}>
            {/* <div style={{padding: '0 10px 10px' }}>
              <Row type="flex" justify="space-around">
                <Col span={12} style={{textAlign:'center'}}><span style={{fontSize:'30px',color:'#4CAF76'}}>{birdGeneral.bird_type_cnt}</span>种</Col>
                <Col span={12} style={{textAlign:'center'}}><span style={{fontSize:'30px',color:'#4CAF76'}}>{birdGeneral.bird_cnt}</span>只</Col>
              </Row>
              <Row type="flex" justify="space-around">
                <Col span={12} style={{textAlign:'center'}}>上月鸟类总量</Col>
                <Col span={12} style={{textAlign:'center'}}>上月鸟类数量</Col>
              </Row>
            </div> */}
            {/* <Divider dashed style={{margin: '10px 0'}}/> */}
            <Row>
                <Col span={7}>
                  <h3 style={{fontSize: '12px', color: '#333', lineHeight: '32px'}}>监测内容:</h3>
                </Col>
                <Col span={17}>
                    <Select
                      showSearch
                      size={'middle'}
                      style={{width: '100%', fontSize: '12px'}}
                      optionFilterProp="children"
                      onChange={this.selectContentChange}
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {conSelectOptions}
                    </Select>
                </Col>
            </Row>
            <div style={{padding: '5px 0px'}}>
              <h3 style={{fontSize: '12px'}}>时间范围:</h3>
              <p className={styles.timeSel}><span className={this.state.timeStatus == 0?styles.active: ''} onClick={()=>this.handleChangeTime(0)}>近三月</span><span className={this.state.timeStatus == 1?styles.active: ''} onClick={()=>this.handleChangeTime(1)}>近两月</span><span className={this.state.timeStatus == 2?styles.active: ''} onClick={()=>this.handleChangeTime(2)}>近半年</span></p>
              <RangePicker key={this.state.timeStamp+1} size={"middle"} style={{ width: 330,padding: '5px 0px'  }}
                           defaultValue={[moment(this.state.startDateStr, dateFormat), moment(this.state.endDateStr, dateFormat)]}
                           format={dateFormat}
                           onChange={this.dataChange} />
            </div>
            {/* <div style={{padding: '10px 0px',height:(bodyHeight - 422) }}>
              <h3 style={{fontSize: '12px', marginBottom: '10px'}}>鸟类品种:</h3>
              <div style={{overflowY: 'auto',overflowX:'hidden',height:'90%' }}>
              {birdRowList}
              </div>
            </div> */}
            <div style={{padding: '5px 0' }}>
              <Button type="primary" size={'middle'} onClick={this.birdCount} block>
                开始分析
              </Button>
            </div>
          </div>
        </Sider>
        <Layout style={{ padding: '0' }}>
          <Content
            style={{
              background: '#fff',
              padding: 0,
              margin: 0,
              minHeight: 280,
            }}
          >
            <div id="birdsMonitoringMap" style={{height: this.state.height}}></div>
          </Content>
        </Layout>
      </Layout>

    );
  }
}

export default BirdsMonitoring;
